﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MiniIOC.IOCLIbs
{
    public class ServiceProviderFactory : IServiceProviderFactory
    {
        private readonly IServiceCollection _services;

        public ServiceProviderFactory(IServiceCollection services)
        {
            _services = services;
        }

        public ServiceProvider CreateServiceProvider()
        {
            ServiceProvider serviceProvider = new ServiceProvider();
            
            foreach (var service in _services)
            {
                serviceProvider.ServiceDescriptors.TryAdd(service.ServiceType!, service);
            }

            Type type = typeof(IServiceProvider);
            serviceProvider.ServiceDescriptors.TryAdd(type, new ServiceDescriptor
            {
                ImplementationInstance = serviceProvider,
                ImplementationType = typeof(ServiceProvider),
                ServiceType = type,
                Lifetime = ServiceLifetime.Singleton,
            });

            return serviceProvider;
        }
    }
}
